package com.laicunba.event.listener;

import java.util.Map;

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.constant.AttributeConstant;
import com.laicunba.event.UserLoginEvent;
import com.laicunba.pojo.UserDO;
import com.laicunba.pojo.vo.UserLoginTokenVO;
import com.laicunba.service.mq.ActiveMQMessageFactory;
import com.laicunba.service.mq.ActiveMQService;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.RedisUtil;

@Component
public class UserLoginEventListener implements ApplicationListener<UserLoginEvent> {
	private static final Logger LOG = Logger.getLogger(UserLoginEventListener.class);

	@Autowired
	private ActiveMQService activeMQService;

	@Override
	public void onApplicationEvent(UserLoginEvent event) {
		UserLoginTokenVO userToken = (UserLoginTokenVO) event.getSource();

		// 发消息
		JSONObject msg = ActiveMQMessageFactory.createUsrLoginMessage(userToken);
		activeMQService.sendTopics("lcb.core.usr.login", msg.toJSONString());

		if(userToken.getUserId().startsWith("TEST.")){
			return;
		}
		
		String key = AttributeConstant.USER_TOKENS.concat(userToken.getUserId());
		Map<String, String> tokens = RedisUtil.hgetAll(key);
		RedisUtil.del(key);
		RedisUtil.hset(key, userToken.getToken(), "");
		if (tokens != null && !tokens.isEmpty()) {
			for (String token : tokens.keySet()) {
				CacheUtil.removeAttribute(AttributeConstant.USER_LOGIN_TOKEN + token);
			}
		}
	}
}
